package app.sceledroid.network;

import java.io.IOException;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import app.sceledroid.R;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import app.sceledroid.entity.User;
import app.sceledroid.exception.CookieFetcherException;

public class CookieFetcher extends AsyncTask<Void, Integer, String> {

	private Context context;
	private DefaultHttpClient client;
	private ProgressDialog dialog;

	public CookieFetcher(Context context, DefaultHttpClient client) {
		super();
		this.context = context;
		this.client = client;
		this.dialog = new ProgressDialog(context);
	}

	@Override
	protected void onPostExecute(String result) {
		// TODO Auto-generated method stub
		super.onPostExecute(result);
		dialog.dismiss();
	}

	@Override
	protected void onPreExecute() {
		// TODO Auto-generated method stub

		super.onPreExecute();
		dialog.setMessage("Fetching Cookies...");
		
		dialog.setIndeterminate(true);
		dialog.setCancelable(false);
		dialog.show();
	}

	@Override
	protected void onProgressUpdate(Integer... values) {
		// TODO Auto-generated method stub
		super.onProgressUpdate(values);
		//dialog.setProgress(values[0]);
	}

	@Override
	protected String doInBackground(Void... params) {
		// TODO Auto-generated method stub
		try {
			//String URL = context.getText(R.string.INDEX_URL).toString();
			//Log.v("URL : " , URL);
			String URL = "http://scele.cs.ui.ac.id";
			HttpGet request = new HttpGet(URL);
			HttpResponse response = client.execute(request);
			Document doc = Jsoup.parse(response.getEntity().getContent(), "UTF-8",URL);
			List<Cookie> cStore = client.getCookieStore().getCookies();
			
			for(Cookie c : cStore)
			{
				Log.v("Cookie", c.getName() + c.getValue());
			}	
			Elements elements = doc.select("tr td p");
			for (Element c : elements) {
				if (c.text().contains("Error")) {
					return new String("Scele Down!");
				}
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			Log.v("CookieFetcher", e.getMessage());
			//Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			//Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show();
			Log.v("CookieFetcher", e.getMessage());
		}

		return null;
	}

}

